package com.example.springboottransaction.service;

import com.example.springboottransaction.pojo.Student;
import com.example.springboottransaction.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Transactional(propagation = Propagation.REQUIRED)
    public Student addStudent(String name, String sex) {
        Student student = Student.builder().name(name).sex(sex).build();
        studentRepository.insertStudent(student);
        //测试异常时的处理
        int a = 10 / 0;
        return studentRepository.findStudentByNear();
    }


    @Transactional(readOnly = false)
    public List<Student> testReadOnlyTrue() {
        return studentRepository.testReadOnlyTrue();
    }

    //------------------------------@Transactional失效的场景------------------------------------//

    /**
     * 非public修饰的方式@Transactional不会起作用
     *
     * @param name
     * @param sex
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    Student addStudents(String name, String sex) {
        Student student = Student.builder().name(name).sex(sex).build();
        studentRepository.insertStudent(student);
        //测试异常时的处理
        int a = 10 / 0;
        return studentRepository.findStudentByNear();
    }

    /**
     * 在类内部调用调用类内部@Transactional标注的方法。这种情况下也会导致事务不开启
     */
    public void testInnerInvoke() {
        addStudent("思考上帝", "女");
    }

    /**
     * 事务方法内部捕捉了异常，没有抛出新的异常，导致事务操作不会进行回滚
     */
    @Transactional
    public void insertTestCatchException() {
        try {
            Student student = Student.builder().name("skdj").sex("sdkj").build();
            studentRepository.insertStudent(student);
            //运行期抛出异常
            throw new RuntimeException("need exception");
        } catch (Exception e) {
            System.out.println("抛出异常");
        }
    }
}
